package com.ruicar.afs.cloud.apply.pre.loan.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.business.service.ApplySignHistoryService;
import com.ruicar.afs.cloud.apply.business.service.ApplySignRelationService;
import com.ruicar.afs.cloud.apply.business.service.ApplySmsSendService;
import com.ruicar.afs.cloud.apply.common.condition.SendMessageCondition;
import com.ruicar.afs.cloud.apply.common.entity.ApplyCustBaseInfo;
import com.ruicar.afs.cloud.apply.common.entity.ApplyOrderInfo;
import com.ruicar.afs.cloud.apply.common.entity.ApplySignHistory;
import com.ruicar.afs.cloud.apply.common.entity.ApplySignRelation;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyAppSignAgreeMentCondition;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyAppSignPeopleListCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyAppService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyCustBaseInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyOrderInfoService;
import com.ruicar.afs.cloud.bizcommon.cfca.dto.CfCaSignatureDto;
import com.ruicar.afs.cloud.bizcommon.print.entity.ComPrintFormManage;
import com.ruicar.afs.cloud.bizcommon.print.service.ComPrintFormManageService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.ruicar.afs.cloud.apply.common.utils.ApplyConstants.*;

/**
 * description: 进件签约协议
 * @date: 2020/8/6 14:28
 * @author mingzhi.li
 */
@Slf4j
@RestController
@RequestMapping("/applyAppSign")
@AllArgsConstructor
public class ApplyAppSignController {

    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ComAttachmentFileService attachmentFileService;
    private final ApplySignHistoryService applySignHistoryService;
    private final ApplySmsSendService applySmsSendService;
    private final ApplyAppService applyAppService;
    private final ApplySignRelationService applySignRelationService;
    private final ApplyOrderInfoService applyOrderInfoService;
    private final ComPrintFormManageService comPrintFormManageService;

    @RequestMapping(value = "/getApplyAppSignPeopleList", method = RequestMethod.POST)
    @ApiOperation(value = "获取签约人列表")
    public IResponse<Object> getApplyAppSignPeopleList(@RequestBody ApplyAppSignPeopleListCondition condition) {
        List<ApplyAppSignPeopleListCondition> conditionList = new ArrayList<>();
        List<ApplyCustBaseInfo> custList = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, condition.getApplyNo()));
        if(custList !=null && custList.size()>0){
            ApplyOrderInfo applyOrderInfo = applyOrderInfoService.getOne(Wrappers.<ApplyOrderInfo>query().lambda().eq(ApplyOrderInfo::getApplyNo, condition.getApplyNo()));
            for(ApplyCustBaseInfo baseInfo :custList ){
                ApplyAppSignPeopleListCondition peopleListCondition = new ApplyAppSignPeopleListCondition();
                //申请编号
                peopleListCondition.setApplyNo(baseInfo.getApplyNo());
                //客户姓名
                peopleListCondition.setCustName(baseInfo.getCustName());
                //证件号码
                peopleListCondition.setCertNo(baseInfo.getCertNo());
                //角色
                peopleListCondition.setCustRole(baseInfo.getCustRole());
                //手机号码
                peopleListCondition.setTelPhone(baseInfo.getTelPhone());
                //签约人主键id
                peopleListCondition.setId(baseInfo.getId());
                //签约错误次数
                int signFailNumber =  baseInfo.getSignFailNumber() == null ? 0 : baseInfo.getSignFailNumber();
                peopleListCondition.setSignFailNumber(signFailNumber);

                if(PRINCIPAL_BORROWER.equals(baseInfo.getCustRole())){
                    if(StrUtil.isBlank(baseInfo.getReappearFlag())){
                        peopleListCondition.setMainManReappearFlag(NO);
                    }else{
                        peopleListCondition.setMainManReappearFlag(baseInfo.getReappearFlag());
                    }
                }else if(COMMON_BORROWER.equals(baseInfo.getCustRole())){
                    if(StrUtil.isBlank(baseInfo.getReappearFlag())){
                        peopleListCondition.setWereBorrowedReappearFlag(NO);
                    }else{
                        peopleListCondition.setWereBorrowedReappearFlag(baseInfo.getReappearFlag());
                    }
                }else if(GUARANTOR.equals(baseInfo.getCustRole())){
                    if(StrUtil.isBlank(baseInfo.getReappearFlag())){
                        peopleListCondition.setGuarantorReappearFlag(NO);
                    }else{
                        peopleListCondition.setGuarantorReappearFlag(baseInfo.getReappearFlag());
                    }
                }
                if(StrUtil.isBlank(applyOrderInfo.getReappearFlag())){
                    peopleListCondition.setReappearFlag(NO);
                }else{
                    peopleListCondition.setReappearFlag(applyOrderInfo.getReappearFlag());
                }
                //关联签约关系表
                List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                        .eq(ApplySignRelation::getCustId, baseInfo.getId())
                        .eq(ApplySignRelation::getBusinessNo,condition.getApplyNo()));
                if(signRelationList !=null && signRelationList.size()>0){
                    for(ApplySignRelation relation: signRelationList){
                        if(NO.equals(relation.getStatus()) || StrUtil.isBlank(relation.getStatus())){
                            peopleListCondition.setSignState(NO);
                            break;
                        }else{
                            peopleListCondition.setSignState(YES);
                            peopleListCondition.setSignDate(relation.getUpdateTime());
                        }
                    }
                }

                conditionList.add(peopleListCondition);
            }
        }
        return IResponse.success(conditionList);
    }

    @RequestMapping(value = "/getApplyAppSignAgreement", method = RequestMethod.POST)
    @ApiOperation(value = "获取签约协议")
    public IResponse<Object> getApplyAppSignAgreement(@RequestBody ApplyAppSignAgreeMentCondition condition) {
        if(StrUtil.isBlank(condition.getApplyNo())){
            return IResponse.fail("申请编号不能为空");
        }
        if(StrUtil.isBlank(condition.getCertNo())){
            return IResponse.fail("证件号码不能为空");
        }
        if(StrUtil.isBlank(condition.getBusinessType())){
            return IResponse.fail("业务类型不能为空");
        }
        if(condition.getCustId()==null){
            return IResponse.fail("客户id不能为空");
        }
        List<ComAttachmentFile>  fileList = applyAppService.getApplyFileList(condition);
        if(fileList ==null || fileList.size()==0){
            return IResponse.fail("签约文件不存在！");
        }

        return IResponse.success(fileList);
    }

    @RequestMapping(value = "/undoApplyAppSignAgreement", method = RequestMethod.POST)
    @ApiOperation(value = "撤销已签约协议")
    public IResponse<Object> undoApplyAppSignAgreement(@RequestBody ApplyAppSignAgreeMentCondition condition) {
        if(StrUtil.isBlank(condition.getApplyNo())){
            return IResponse.fail("申请编号不能为空");
        }
        if(condition.getCustomerId() ==null||condition.getCustomerId().length==0){
            return IResponse.fail("客户id不能为空");
        }

        List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                .in(ApplySignRelation::getCustId, Arrays.asList(condition.getCustomerId()))
                .eq(ApplySignRelation::getBusinessNo,condition.getApplyNo()));
        if(signRelationList !=null && signRelationList.size()>0){
            for(ApplySignRelation relation:signRelationList){
                List<ApplySignHistory> applySignHistoryList = applySignHistoryService.list(Wrappers.<ApplySignHistory>query().lambda()
                        .eq(ApplySignHistory::getRelationId, relation.getId())
                        .eq(ApplySignHistory::getBusinessNo,condition.getApplyNo()));
                if(applySignHistoryList !=null && applySignHistoryList.size()>0){
                    for(ApplySignHistory history :applySignHistoryList){
                        List<ComAttachmentFile> comAttachmentFileList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                                .eq(ComAttachmentFile::getId, history.getFileId().toString()));
                        if(comAttachmentFileList !=null && comAttachmentFileList.size()>0){
                            //1.删除附件信息表数据
                            for(ComAttachmentFile file :comAttachmentFileList){
                                log.info("删除附件信息表对应模版数据"+file);
                                attachmentFileService.removeById(file);
                            }
                        }
                        log.info("删除签约历史信息表对应模版数据"+history);
                        //2.删除签约历史信息表数据
                        applySignHistoryService.removeById(history);

                        //3.删除合同模版合同对应附件信息
                        ComPrintFormManage info = comPrintFormManageService.getOne(Wrappers.<ComPrintFormManage>query().lambda().eq(ComPrintFormManage::getId, history.getTempleId()));
                        if(info !=null){
                            List<ComAttachmentFile> fileList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                                    .eq(ComAttachmentFile::getBusiNo, condition.getApplyNo())
                                    .eq(ComAttachmentFile::getAttachmentCode,info.getAscriptionSubClass()));
                            if(fileList !=null && fileList.size()>0){
                                for(ComAttachmentFile file :comAttachmentFileList){
                                    log.info("删除附件信息表对应模版数据"+file);
                                    attachmentFileService.removeById(file);
                                }
                            }
                        }
                    }
                }
                //4.修改合同签约关系表状态：未签约
                relation.setStatus(NO);
                relation.setUpdateTime(null);
                applySignRelationService.updateById(relation);
            }
        }
        return IResponse.success("删除成功");
    }

    @RequestMapping(value = "/sendApplyAppSignMessage", method = RequestMethod.POST)
    @ApiOperation(value = "发送签约短信")
    public IResponse<Object> sendApplyAppSignMessage(@RequestBody SendMessageCondition condition) {
        if(USAGESCENARIOS_TYPE_ONE.equals(condition.getUsageScenarios())||USAGESCENARIOS_TYPE_TWO.equals(condition.getUsageScenarios())){
            if(StrUtil.isBlank(condition.getApplyNo())){
                return IResponse.fail("申请编号不能为空");
            }
            if(condition.getCustId()==null){
                return IResponse.fail("客户id不能为空");
            }
        }
        if(StrUtil.isBlank(condition.getTelPhone())){
            return IResponse.fail("手机号码不能为空");
        }
        if(StrUtil.isBlank(condition.getCertNo())){
            return IResponse.fail("证件号码不能为空");
        }
        if(StrUtil.isBlank(condition.getMessageType())){
            return IResponse.fail("短信类型不能为空");
        }
        if(StrUtil.isBlank(condition.getUsageScenarios())){
            return IResponse.fail("短信使用场景不能为空");
        }
        if(USAGESCENARIOS_TYPE_ZERO.equals(condition.getUsageScenarios())){
            if(StrUtil.isBlank(condition.getBusinessType())){
                return IResponse.fail("业务类型不能为空");
            }
        }
        IResponse verCode= applySmsSendService.send(condition);
        return verCode;
    }

    @RequestMapping(value = "/checkApplyAppSignMessage", method = RequestMethod.POST)
    @ApiOperation(value = "核对签约验证码")
    public IResponse<Object> checkApplyAppSignMessage(@RequestBody SendMessageCondition condition) {
        if(USAGESCENARIOS_TYPE_ONE.equals(condition.getUsageScenarios())||USAGESCENARIOS_TYPE_TWO.equals(condition.getUsageScenarios())){
            if(StrUtil.isBlank(condition.getApplyNo())){
                return IResponse.fail("申请编号不能为空");
            }
            if(condition.getCustId()==null){
                return IResponse.fail("客户id不能为空");
            }
        }
        if(StrUtil.isBlank(condition.getTelPhone())){
            return IResponse.fail("手机号码不能为空");
        }
        if(StrUtil.isBlank(condition.getCertNo())){
            return IResponse.fail("证件号码不能为空");
        }
        if(StrUtil.isBlank(condition.getMessageType())){
            return IResponse.fail("短信类型不能为空");
        }
        if(!MESSAGE_TYPE_ONE.equals(condition.getMessageType())&& !MESSAGE_TYPE_TWO.equals(condition.getMessageType())){
            return IResponse.fail("短信类型不存在");
        }
        if(StrUtil.isBlank(condition.getUsageScenarios())){
            return IResponse.fail("短信使用场景不能为空");
        }
        if(StrUtil.isBlank(condition.getRandomCode())){
            return IResponse.fail("短信验证码不能为空");
        }
        if(USAGESCENARIOS_TYPE_ZERO.equals(condition.getUsageScenarios())){
            if(StrUtil.isBlank(condition.getBusinessType())){
                return IResponse.fail("业务类型不能为空");
            }
        }
        IResponse verCode= applySmsSendService.check(condition);
        return verCode;
    }

    @RequestMapping(value = "/electronicSignature", method = RequestMethod.POST)
    @ApiOperation(value = "电子签名")
    public IResponse  electronicSignature(@RequestBody CfCaSignatureDto dto) {

        if(dto.getFileId() ==null && dto.getFileId().length==0){
            return IResponse.fail("文件id不能为空");
        }
        if(dto.getCustId() ==null){
            return IResponse.fail("客户id不能为空");
        }
        if(dto.getFile() ==null && dto.getFile().length==0){
            return IResponse.fail("签约图片不能为空");
        }
        if(StrUtil.isBlank(dto.getSignScene())){
            return IResponse.fail("签约场景不能为空");
        }

        if(StrUtil.isBlank(dto.getApplyNo())){
            return IResponse.fail("附件编号不能为空");
        }
        log.info("签约文件合成开始");
        IResponse iResponse = applyAppService.electronicSignature(dto);
        if(!Boolean.TRUE.equals(iResponse.getData())){
            return IResponse.fail("签约失败");
        }else{
            return IResponse.success("签约成功");
        }
    }

    @RequestMapping(value = "/getPreAppSignAgreement", method = RequestMethod.POST)
    @ApiOperation(value = "获取预审批签约协议")
    public IResponse<Object> getPreAppSignAgreement(@RequestBody ApplyAppSignAgreeMentCondition condition) {
        if(condition.getPreId()==null){
            return IResponse.fail("预审客户id不能为空");
        }
        //预审批
        condition.setSignScene(MESSAGE_TYPE_ZERO);
        List<ComAttachmentFile>  fileList = applyAppService.getPreFileList(condition);
        if(fileList ==null || fileList.size()==0){
            return IResponse.fail("签约文件不存在！");
        }
        return IResponse.success(fileList);
    }
}
